package com.gosling.gosling.ziruan;

import com.gosling.cloudspace.common.entity.pojo.UserInfoPO;
import com.gosling.cloudspace.common.service.UserInfoService;
import com.gosling.cloudspace.tools.IOTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.xml.sax.SAXException;
import org.xml.sax.ext.Attributes2Impl;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.*;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Software: IntelliJ IDEA
 * @Addresses: www.gosling.com
 * @Email 1793327033@qq.com
 * @Classname lhltest
 * @Author: lihonglin
 * @Date: 2021/8/8 17:36
 */
@SuppressWarnings("all")
@SpringBootTest(classes = ZiRuanXmlTest.class)
@SpringBootApplication
public class ZiRuanXmlTest {

    @Autowired
    UserInfoService userInfoService;

//    public static void main(String[] args) {
////        HashMap<Object, Object> map = new HashMap<>();
////        //map.put(null,null);
////        map.get(null);
////
////        String sss = "11111121212";
////
////        String[] split = sss.split("[|]");
////        for (String s : split) {
////            System.out.println(s);
////        }
//
//        String tradeLimit = "1,2";
//        tradeLimit = tradeLimit.replace("1", "消费")
//                .replace("2", "出款")
//                .replace("3", "个人提现")
//                .replace("4", "分账退款");
//        System.out.println(tradeLimit);
//    }

    public static void test14() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        FileWriter out = null;
        XMLWriter xmlWriter = null;
        XMLEventReader reader = null;
        try {
            is = new FileInputStream("D:\\123456.xml");
            out = new FileWriter("D:\\1234567.xml");
            reader = factory.createXMLEventReader(is);
            Document document = DocumentHelper.createDocument();
            Element element = document.addElement("电子文件封装包", "http://www.saac.gov.cn/standards/ERM/encapsulation");
            xmlWriter = new XMLWriter(out, OutputFormat.createPrettyPrint());
            setElement2(element, reader);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
            IOTool.closeQuietly(reader);
            IOTool.closeQuietly(xmlWriter);
            IOTool.closeQuietly(out);
        }
    }

    private static void setElement2(Element element, XMLEventReader reader) throws XMLStreamException, SAXException,
            IOException {
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            String charactersData = null;
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                String name = startElement.getName().getLocalPart();
                Iterator attributes = startElement.getAttributes();
                Attributes2Impl attr = new Attributes2Impl();
                while (attributes.hasNext()) {
                    Attribute attribute = (Attribute) attributes.next();
                    String localPart = attribute.getName().getLocalPart();
                    String value = attribute.getValue();
                    String dtdType = attribute.getDTDType();
                    attr.addAttribute(null, localPart, localPart, dtdType, value);
                }
                if (name.equals("编码数据")) {
                    String refId = null;
                    for (int i = 0; i < attr.getLength(); i++) {
                        String refIdOrEncodeId = attr.getValue(i);
                        if (refIdOrEncodeId.equals("引用编码数据ID")) {
                            refId = refIdOrEncodeId;
                        }
                    }
                    if (refId == null) {
                        Element addElement = element.addElement(name);
                        addElement.addText("");
                    } else {
                        Element addElement = element.addElement(name);
                        addElement.addText("");
                    }
                } else {
                    XMLEvent xmlEvent = reader.nextEvent();
                    if (xmlEvent.getEventType() == XMLStreamConstants.CHARACTERS) {
                        if (!xmlEvent.asCharacters().isWhiteSpace()) {
                            Characters characters = xmlEvent.asCharacters();
                            charactersData = characters.getData();
                        } else {
                            charactersData = "";
                        }
                    }
                    Element addElement = element.addElement(name);
                    if (charactersData != null) {
                        addElement.addText(charactersData);
                    } else {
                        setElement2(addElement, reader);
                    }
                }
            } else if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                String name = endElement.getName().getLocalPart();
                //xmlWriter.endElement(null, name, name);
            }
        }
    }

    private static void setElement(XMLWriter xmlWriter, XMLEventReader reader, HashMap<String, String> map) throws XMLStreamException,
            SAXException, IOException {
        String old = map.get("old");
        String aNew = map.get("new");
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            String charactersData = null;
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                String name = startElement.getName().getLocalPart();
                Iterator attributes = startElement.getAttributes();
                Attributes2Impl attr = new Attributes2Impl();
                while (attributes.hasNext()) {
                    Attribute attribute = (Attribute) attributes.next();
                    String localPart = attribute.getName().getLocalPart();
                    String value = attribute.getValue();
                    String dtdType = attribute.getDTDType();
                    attr.addAttribute(null, localPart, localPart, dtdType, value);
                }
                if (name.equals("编码数据")) {
                    String refId = null;
                    for (int i = 0; i < attr.getLength(); i++) {
                        String refIdOrEncodeId = attr.getValue(i);
                        if (refIdOrEncodeId.equals("引用编码数据ID")) {
                            refId = refIdOrEncodeId;
                        }
                    }
                    if (refId == null) {
                        xmlWriter.startElement(null, name, name, attr);
                    } else {
                        xmlWriter.startElement(null, name, name, attr);
                        xmlWriter.write("");
                    }
                } else {
                    XMLEvent xmlEvent = reader.nextEvent();
                    if (xmlEvent.getEventType() == XMLStreamConstants.CHARACTERS) {
                        if (!xmlEvent.asCharacters().isWhiteSpace()) {
                            Characters characters = xmlEvent.asCharacters();
                            charactersData = characters.getData();
                        } else {
                            charactersData = "";
                        }
                    }
//               if (name.equals("文件标识符")) {
//                  int eventType = event.getEventType();
//                  boolean characters = event.isCharacters();
//                  QName schemaType = startElement.getSchemaType();
//                  xmlWriter.startElement(null, name + "/", name + "/", attr);
//               } else {
//                  xmlWriter.startElement(null, name, name, attr);
//               }
                    xmlWriter.startElement(null, name, name, attr);
                    if (charactersData != null) {
                        xmlWriter.write(charactersData);
                    } else {
                        setElement(xmlWriter, reader, map);
                    }
                }
            } else if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                String name = endElement.getName().getLocalPart();
                xmlWriter.endElement(null, name, name);
            } else {
                int eventType = event.getEventType();
            }
        }
    }

    @SuppressWarnings("all")
    public static void writeToFile3(String filePath, String fileName) throws Exception {
        Document doc = DocumentHelper.createDocument();
        Element rootElement = doc.addElement("root");
        rootElement.addAttribute("编码ID", "12345");
        Element testElement = DocumentHelper.createElement("eleTest");
        testElement.addAttribute("编码ID", "12345");
        testElement.addText("this is another text");
        testElement.setParent(rootElement);
        XMLWriter out = null;
        try {
            out = new XMLWriter(new FileWriter(new File(filePath + File.separator + fileName)));
            out.startDocument();
            out.startPrefixMapping("", "http://www.saac.gov.cn/standards/ERM/encapsulation");
            out.endPrefixMapping("");
            out.startPrefixMapping("xsi", "http://www.saac.gov.cn/standards/ERM/encapsulation");
            out.endPrefixMapping("");
            Attributes2Impl attributes = new Attributes2Impl();
            attributes.addAttribute("http://www.saac.gov.cn/standards/ERM/encapsulation eep.xsd", "", "xsi:schemaLocation"
                    , "", "http://www.saac.gov.cn/standards/ERM/encapsulation eep.xsd");
            out.startElement("xsi", "qqq", "qwqwq", attributes);
//         out.writeOpen(rootElement);

            out.write(testElement);

            out.write(testElement);
//         out.writeClose(rootElement);
            out.endElement("", "qqq", "qwqwq");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("all")
    public static void writeToFile2(String filePath, String fileName) throws Exception {
        Document doc = DocumentHelper.createDocument();
        Element rootElement = doc.addElement("root");
        rootElement.addAttribute("name", "root");
        Element testElement = DocumentHelper.createElement("eleTest");
        testElement.addAttribute("name", "testEle");
        testElement.addText("this is another text");
        testElement.setParent(rootElement);
//        for (int i = 0; i <= 30000000; i++) {
//            testElement.addElement("test").setText("111111111111111112");
//        }
//      Attributes atts = new AttList()
        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(filePath)));
        XMLWriter out = null;
        try {
            out = new XMLWriter(new FileWriter(new File(filePath + File.separator + fileName)));
            out.startDocument();
            out.writeOpen(rootElement);
            for (int i = 0; i <= 30000000; i++) {
                out.write(testElement);
            }
            out.write(testElement);
            out.writeClose(rootElement);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        BigDecimal totalCharges = BigDecimal.ZERO;
        totalCharges.add(null);
        System.out.println(111);
        System.out.println(111);
        System.out.println(111);
        System.out.println(111);
    }

    /***
     * 循环嵌套解决方案
     */
    private static void innerForEach() {
        List<UserInfoPO> list = new ArrayList<>();
        UserInfoPO userInfoPO = new UserInfoPO();
        userInfoPO.setName("唐三");
        userInfoPO.setImage("哈哈哈");
        list.add(userInfoPO);
        userInfoPO = new UserInfoPO();
        userInfoPO.setName("韩立");
        list.add(userInfoPO);
        List<UserInfoPO> list2 = new ArrayList<>();
        userInfoPO = new UserInfoPO();
        userInfoPO.setName("历飞宇");
        list2.add(userInfoPO);
        userInfoPO = new UserInfoPO();
        userInfoPO.setName("唐三");
        list2.add(userInfoPO);

        HashMap<String, Integer> map1 = new HashMap<>();
        HashMap<String, Integer> map2 = new HashMap<>();
        HashSet<String> set1 = new HashSet<>();
        HashSet<String> set2 = new HashSet<>();

        for (int i = 0; i < list.size(); i++) {
            map1.put(list.get(i).getName(), i);
            set1.add(list.get(i).getName());
        }
        for (int i = 0; i < list2.size(); i++) {
            map2.put(list2.get(i).getName(), i);
            set2.add(list2.get(i).getName());
        }
        Set<String> set = new HashSet<>(set1);
        set.addAll(set1);
        set.retainAll(set2);
        for (String name : set) {
            Integer index = map1.get(name);
            Integer index2 = map2.get(name);
            UserInfoPO pig = list.get(index);
            UserInfoPO pig2 = list2.get(index2);
            pig2.setImage(pig.getImage());
        }
        for (UserInfoPO pig : list2) {
            System.out.println(pig);
        }
    }

    public static boolean isNull(Object... objects) {
        boolean flag = false;
        for (Object object : objects) {
            flag = Objects.isNull(object);
        }
        return flag;
    }

    public static void test4() {
        List<String> ids = new ArrayList<>();
        ids.add("12121");
        ids.add("134561");
        ids.add("8970");
        ids.add("4386");
        StringBuffer where = new StringBuffer();
        String join = String.join(",", ids);
        System.out.println(join.toString());
        ThreadLocal threadLocal = new ThreadLocal();

    }

    public void testMethod3() {
        String archiveId = "35e412e3b4d94c258370e794399d4d0d";
        String tableId = "de9f9128c93843ad8c2949ace320dc62";
        List<LinkedHashMap> electronicRecords = null;
        if (!Objects.isNull(electronicRecords) && electronicRecords.size() > 0) {
            for (LinkedHashMap electronicRecord : electronicRecords) {
                Object tempStatus = electronicRecord.get("temp_status");
                if (!Objects.isNull(tempStatus)) {
                    String tempStatusStr = tempStatus.toString();
                    if (!StringUtils.isBlank(tempStatusStr)) {
                        if ("0".equals(tempStatusStr)) {
                            System.out.println("未保存");
                        }
                    }
                }
            }
        }
    }

    public void testMethod2() {
//        XmlDataPackgeUtils dataPackgeUtils = new XmlDataPackgeUtils();
//        //fondsId       08594c3f003242d39a3b31ed5ac51ba5
//        //archivesId    a7071b2ca62b400d9541fcd56022c823
//        //tableId        9b40f618358f40c088c5af9ff8b41d62
//        //archiveId       1e303e833b0c41798476c0bb249e3ead
//        //tableName     f1_37_document
//        long start = System.currentTimeMillis();
//
//        String tableId = "9b40f618358f40c088c5af9ff8b41d62";
//        String archiveId = "1e303e833b0c41798476c0bb249e3ead";
//        List<String> docids = new ArrayList<>();
//        docids.add("1");
//
//        Result2Xml result = dataPackgeUtils.fileXml(archiveId, tableId);
//        Object data = result.getData();
//        Integer code = result.getCode();
//        String message = result.getMessage();
//        System.out.println(result);
//        System.out.println(data);
//        System.out.println(code);
//        System.out.println(message);
//        System.out.println("运行时间：" + (System.currentTimeMillis() - start));

    }

    ;

    public void test2() {
        Date date = new Date();
        int year = date.getYear();
        int month = date.getMonth();
        int day = date.getDay();
        StringBuffer buf = new StringBuffer();
        StringBuffer append = buf.append(year).append("年").append("/").
                append(month).append("月").append("/").append(day).append("日").append("/");
        System.out.println(append.toString());

        /**
         * 年: 2021
         * 月: 8
         * 日: 23
         */
        Calendar now = Calendar.getInstance();
        System.out.println("年: " + now.get(Calendar.YEAR));
        System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");
        System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
    }

    public void test3() {
//        List<String> ids = new ArrayList<>();
//        ids.add("12121");
//        ids.add("134561");
//        ids.add("8970");
//        ids.add("4386");
        String ids = "21321312321,45645645654";
        StringBuffer where = new StringBuffer();
//        StringBuffer append = where.append(" and vol_id in (" + ids + ")");
        String join = String.join(",", ids);
        join = join.replace(",", "','");
        StringBuffer append = where.append(String.format("  vol_id in ('%s')", ids));
        System.out.println(append.toString());
    }

    public void writeToFile(String filePath, String fileName) {
        Document doc = DocumentHelper.createDocument();
        Element rootElement = doc.addElement("root");
        rootElement.addAttribute("name", "root");
        Element testElement = DocumentHelper.createElement("eleTest");
        testElement.addAttribute("name", "testEle");
        testElement.addText("this is another text");
        testElement.setParent(rootElement);
        XMLWriter out = null;
        try {
            out = new XMLWriter(new FileWriter(new File(filePath + File.separator + fileName)));
            out.startDocument();
            out.writeOpen(rootElement);
            for (int i = 0; i <= 10000000; i++) {
                out.write(testElement);
            }
            out.writeClose(rootElement);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    private void saxReaderSimple(String fileName) throws DocumentException, FileNotFoundException {
        Document doc;
        SAXReader reader = new SAXReader();
        reader.setDefaultHandler(new ElementHandler() {
            public void onEnd(ElementPath ep) {
                Element e = ep.getCurrent();
                System.out.println(e.getName());
                e.detach(); //记得从内存中移去
            }

            public void onStart(ElementPath arg0) {
            }
        });
        doc = reader.read(new BufferedInputStream(new FileInputStream(new File(fileName))));

        reader.setDefaultHandler(new ElementHandler() {
            public void onEnd(ElementPath ep) {
                Element e = ep.getCurrent();
                System.out.println(e.getName());
                e.detach(); //记得从内存中移去
            }

            public void onStart(ElementPath arg0) {
            }
        });
        doc = reader.read(new BufferedInputStream(new FileInputStream(new File(fileName))));
    }


}
